package cn.com.jinhao.hotline.commons.util;

import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import org.apache.poi.hssf.usermodel.HSSFCell;
import org.apache.poi.hssf.usermodel.HSSFCellStyle;
import org.apache.poi.hssf.usermodel.HSSFDataFormat;
import org.apache.poi.hssf.usermodel.HSSFRow;
import org.apache.poi.hssf.usermodel.HSSFSheet;
import org.apache.poi.hssf.usermodel.HSSFWorkbook;


import java.io.File;
import java.io.FileOutputStream;
import java.util.List;
import java.util.UUID;

/**
 * @author Administrator
 */
public class ExeclUtil {

    /**
     * 导出execl表格
     * @param headerList 表头集合
     * @param importArray 导出的对象的集合
     * @param fileUrl  导出地址
     * @return String
     */
    public String exportExecl(List<String> headerList, JSONArray importArray,String fileUrl) {
        File excelFile;
        FileOutputStream fOut = null;
        HSSFWorkbook workbook ;
        String uuid = UUID.randomUUID().toString();
        if (headerList.isEmpty()) {
            return "Execl表头不能为空";
        }
        try {
            excelFile = File.createTempFile(uuid, ".xls", new File(fileUrl));
            //声明工作薄
            workbook = new HSSFWorkbook();
            //生成表格
            HSSFSheet sheet = workbook.createSheet();

            HSSFRow rowHand = sheet.createRow(0);
            int heraderCount = 0;
            for (String str : headerList) {
                HSSFCell cellHead = rowHand.createCell(heraderCount);
                cellHead.setCellValue(str);
                heraderCount++;
            }
            //设置表格主内容
            //单元格格式的创建需在循环体外，不然数据量过大时会报错
            HSSFCellStyle textStyle = workbook.createCellStyle();
            //用于格式化单元格的数据
            HSSFDataFormat format = workbook.createDataFormat();
            //设置为单元格文本格式
            textStyle.setDataFormat(format.getFormat("@"));
            //不换行
            textStyle.setWrapText(false);
            //行数据
            int importRow = 0;
            for (Object o : importArray) {
                HSSFRow row = sheet.createRow(importRow + 1);
                JSONObject jsonObject = (JSONObject) o;
                //列数据
                int importCell = 0;
                for (String str : headerList) {
                    HSSFCell cell = row.createCell(importCell);
                    cell.setCellValue(jsonObject.get(str).toString());
                    importCell++;
                }
                importRow++;
            }
            fOut = new FileOutputStream(excelFile);
            //写内容，xls文件已经可以打开
            workbook.write(fOut);
            //刷新缓冲区
            fOut.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            try {
                if (fOut != null){
                    fOut.close();
                }
            } catch (Exception e) {
                e.printStackTrace();
            }
        }
        return fileUrl+"\\"+uuid+".xls";
    }
}
